const fs = require('fs');
const path = require('path');

// 读取原始JS文件
const wasmJsPath = path.join(__dirname, 'dist', 'web', 'calculator.js');
let jsCode = fs.readFileSync(wasmJsPath, 'utf8');

console.log('原始代码前50行:');
console.log(jsCode.split('\n').slice(0, 50).map((line, i) => `${i+1}: ${line}`).join('\n'));

// 应用替换
jsCode = jsCode
    .replace(/export default Module;/g, 'return Module;')
    .replace(/import\.meta\.url/g, '"file://" + __filename')
    .replace(/async function Module\(moduleArg = \{\}\)/g, 'function Module(moduleArg)')
    .replace(/function sharedRegisterType\(rawType, registeredInstance, options = \{\}\)/g, 'function sharedRegisterType(rawType, registeredInstance, options) { options = options || {};')
    .replace(/function registerType\(rawType, registeredInstance, options = \{\}\)/g, 'function registerType(rawType, registeredInstance, options) { options = options || {};')
    .replace(/moduleArg \|\|= \{\}/g, 'moduleArg = moduleArg || {}')
    .replace(/if \(ENVIRONMENT_IS_NODE\) \{[\s\S]*?\}/g, 'if (ENVIRONMENT_IS_NODE) {\n  // require已经通过参数提供\n  var require = nodeRequire;\n}')
    .replace(/await import\('module'\)/g, 'require("module")')
    .replace(/await /g, '')
    .replace(/warnOnce\.shown \|\|= \{\}/g, 'warnOnce.shown = warnOnce.shown || {}');

console.log('\n\n替换后代码前50行:');
console.log(jsCode.split('\n').slice(0, 50).map((line, i) => `${i+1}: ${line}`).join('\n'));

// 尝试创建函数
try {
    const moduleFunction = new Function('nodeRequire', '__filename', '__dirname', 'process', jsCode);
    console.log('\n✅ 函数创建成功');
} catch (error) {
    console.log('\n❌ 函数创建失败:', error.message);
    
    // 查找包含=的行
    const lines = jsCode.split('\n');
    console.log('\n包含=的前20行:');
    lines.forEach((line, i) => {
        if (line.includes('=') && i < 100) {
            console.log(`${i+1}: ${line}`);
        }
    });
}